package com.suyang.syt.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.suyang.syt.dao.interfaces.CitysDao;
import com.suyang.syt.model.Citys;
import com.suyang.syt.model.dto.AjaxObj;
import com.suyang.syt.model.dto.CitysDTO;
import com.suyang.syt.model.dto.app.AppCitysDTO;
import com.suyang.syt.service.interfaces.CitysService;
import com.suyang.syt.util.BaiduMapUtil;
import com.suyang.syt.util.EmptyUtil;
import com.suyang.syt.util.PinyinUtil;

@Service
public class CitysServiceImpl implements CitysService {
	private Logger logger = Logger.getLogger(CitysServiceImpl.class);

	@Autowired
	private CitysDao citysDao;

	@Override
	public List<CitysDTO> list(long id) throws Exception {
		List<Citys> list = citysDao.list("from Citys c where c.pid=?", id);
		if (EmptyUtil.isNotEmpty(list)) {
			List<CitysDTO> temp = new ArrayList<CitysDTO>();
			for (Citys citys : list) {
				temp.add(new CitysDTO(citys));
			}
			return temp;
		}
		return null;
	}

	@Override
	public AjaxObj add(CitysDTO citysDTO) throws Exception {
		if (citysDTO != null) {
			if (EmptyUtil.isEmpty(citysDTO.getCode())) {
				return new AjaxObj(0, "编号不能为空！");
			}
			if (citysDao.theExistenceNumber(citysDTO.getCode())) {
				return new AjaxObj(0, "已经存在该编号，请更换编号！");
			}
			if (EmptyUtil.isEmpty(citysDTO.getText())) {
				return new AjaxObj(0, "名称不能为空！");
			}
			if (citysDao.theExistenceName(citysDTO.getText())) {
				return new AjaxObj(0, "已经存在该名称，请更换名称！");
			}
			Citys parent = citysDao.load(citysDTO.getPid());
			if (parent == null) {
				return new AjaxObj(0, "读取上级行政区域错误，请联系管理员！");
			}
			if ("open".equals(parent.getState())) {
				parent.setState("closed");
			}
			citysDao.update(parent);
			Citys citys = new Citys();
			citys.setPid(parent.getId());
			citys.setPtext(parent.getText());
			citys.setCode(citysDTO.getCode());
			citys.setState("open");
			citys.setText(citysDTO.getText());
			citys.setQuanpin(PinyinUtil.str2Pinyin(citysDTO.getText(), null));
			citys.setJianpin(PinyinUtil.strFirst2Pinyin(citysDTO.getText()).toUpperCase());
			citysDao.add(citys);
			return new AjaxObj(1, "添加成功！", citys);
		}
		return new AjaxObj(0, "添加失败！");
	}

	@Override
	public AjaxObj delete(String ids) throws Exception {
		if (EmptyUtil.isNotEmpty(ids)) {
			String[] idss = ids.split(",");
			if (idss != null && idss.length > 0) {
				for (String id : idss) {
					if ("1".equals(id)) {
						return new AjaxObj(0, "对不起，不能删除根节点！");
					}
				}
				for (String id : idss) {
					delete(citysDao.load(id));
				}
				return new AjaxObj(1, "删除成功！");
			}
		} else {
			return new AjaxObj(0, "请选择要删除的记录！");
		}
		return new AjaxObj(0, "删除失败！");
	}

	private void delete(Citys citys) {
		if (citys != null) {
			List<Citys> list = citysDao.list(" from Citys c where c.pid=? ", citys.getId());
			if (EmptyUtil.isNotEmpty(list)) {
				for (Citys ic : list) {
					delete(ic);
				}
			}
			citysDao.delete(citys);
		}
	}

	@Override
	public AjaxObj update(CitysDTO citysDTO) throws Exception {
		if (citysDTO != null) {
			if (citysDTO.getId() == 1) {
				return new AjaxObj(0, "对不起，不能更新根节点！");
			}
			if (citysDTO.getId() < 1) {
				return new AjaxObj(0, "ID不能为空！");
			}
			Citys citys = citysDao.load(citysDTO.getId());
			if (citys == null) {
				return new AjaxObj(0, "读取行政区域错误，请联系管理员！");
			}
			if (EmptyUtil.isEmpty(citysDTO.getText())) {
				return new AjaxObj(0, "名称不能为空！");
			}
			if (!citysDTO.getText().equals(citys.getText()) && citysDao.theExistenceName(citysDTO.getText())) {
				return new AjaxObj(0, "已经存在该名称，请更换名称！");
			}
			if (EmptyUtil.isEmpty(citysDTO.getCode())) {
				return new AjaxObj(0, "编号不能为空！");
			}
			if (!citysDTO.getCode().equals(citys.getCode()) && citysDao.theExistenceNumber(citysDTO.getCode())) {
				return new AjaxObj(0, "已经存在该编号，请更换编号！");
			}
			long pid = citysDTO.getPid();
			if (pid <= 0) {
				return new AjaxObj(0, "父ID不能为空！");
			}
			Citys parent = citysDao.load(pid);
			if (parent == null) {
				return new AjaxObj(0, "读取上级行政区域错误，请联系管理员！");
			}
			if ("open".equals(parent.getState())) {
				parent.setState("closed");
			}
			citysDao.update(parent);
			citys.setPid(parent.getId());
			citys.setPtext(parent.getText());
			citys.setCode(citysDTO.getCode());
			citys.setText(citysDTO.getText());
			citys.setQuanpin(PinyinUtil.str2Pinyin(citysDTO.getText(), null));
			citys.setJianpin(PinyinUtil.strFirst2Pinyin(citysDTO.getText()).toUpperCase());
			citysDao.update(citys);
			return new AjaxObj(1, "更新成功！", citys);
		}
		return new AjaxObj(0, "更新失败！");
	}

	@Override
	public List<CitysDTO> listGBCT() throws Exception {
		List<CitysDTO> temp = new ArrayList<CitysDTO>();
		List<Citys> list = citysDao.list(" from Citys c where c.text='河南省' order by code ");
		if (EmptyUtil.isNotEmpty(list)) {
			for (Citys citys : list) {
				temp.add(listChildren(citys));
			}
		}
		return temp;
	}

	/** 递归调用得到所有子节点 */
	private CitysDTO listChildren(Citys citys) {
		if (citys != null) {
			CitysDTO citysDTO = new CitysDTO(citys);
			List<Citys> children = citysDao.list(" from Citys c where c.pid=? order by code ", citys.getId());
			List<CitysDTO> temp = new ArrayList<CitysDTO>();
			for (Citys tempCitys : children) {
				temp.add(listChildren(tempCitys));
			}
			citysDTO.setChildren(temp);
			return citysDTO;
		}
		return null;
	}

	@Override
	public List<CitysDTO> findGBCT(String q) throws Exception {
		List<CitysDTO> temp = null;
		if (EmptyUtil.isNotEmpty(q)) {
			temp = new ArrayList<CitysDTO>();
			List<Citys> list = citysDao.list(" from Citys c where c.jianpin like ? and c.state='closed' order by code ", q.toUpperCase() + "%");
			if (EmptyUtil.isNotEmpty(list)) {
				for (Citys citys : list) {
					temp.add(listChildren(citys));
				}
			}
		}
		return temp;
	}

	@Override
	public Citys getByName(String name) throws Exception {
		List<Citys> list = citysDao.list("from Citys c where c.text=?", name);
		if (EmptyUtil.isNotEmpty(list)) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public List<Citys> findByPid(long pid) throws Exception {
		return citysDao.list("from Citys c where c.pid=? and c.status=1", pid);
	}

	@Override
	public AjaxObj updateApproved(String ids, int status) throws Exception {
		if (EmptyUtil.isNotEmpty(ids)) {
			String[] idsArr = ids.split(",");
			for (String id : idsArr) {
				updateApprovedRecursive(Long.parseLong(id), id + ",", status);
			}
			return new AjaxObj(1, "改变城市开通状态成功！");
		}
		return new AjaxObj(0, "改变城市开通状态失败！");
	}

	/** 递归更新该城市下所有行政区域的开通状态 */
	private void updateApprovedRecursive(long cid, String ids, int status) {
		if (cid > 1) {
			List<Citys> children = citysDao.list(" from Citys c where c.pid=? order by code ", cid);
			if (EmptyUtil.isNotEmpty(children)) {
				for (Citys citys : children) {
					ids += citys.getId() + ",";
					updateApprovedRecursive(citys.getId(), ids, status);
				}
				citysDao.updateStatus(ids.substring(0, ids.length() - 1), status);
			}
		}
	}

	@Override
	public AjaxObj findArea(double lat, double lng) throws Exception {
		List<AppCitysDTO> datas = null;
		List<Citys> list = null;
		String msg = "";
		try {
			if (lat == 0 && lng == 0) {
				msg = "获取默认城市郑州的区域成功!";
				list = findByPid(3);
			} else {
				Map<String, String> map = BaiduMapUtil.findArea(lat, lng);
				String name = map.get("city");
				Citys cityProvince = getByName(map.get("province"));
				Citys cityCity = getByName(name);
				Citys cityDistrict = getByName(map.get("district"));
				if (cityDistrict.getPid() == cityCity.getId() && cityCity.getPid() == cityProvince.getId()) {
					if (cityCity.getStatus() != 1) {
						return new AjaxObj(0, "当前城市没有开通!");
					}
					list = findByPid(cityCity.getId());
					if (EmptyUtil.isNotEmpty(list)) {
						datas = new ArrayList<AppCitysDTO>();
						AppCitysDTO appCitysDTO = null;
						for (Citys citys : list) {
							appCitysDTO = new AppCitysDTO(citys);
							appCitysDTO.setPname(name);
							datas.add(appCitysDTO);
						}
						return new AjaxObj(1, map.get("msg"), datas);
					}
				}
				return new AjaxObj(0, map.get("msg"));
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			msg = "获取默认城市郑州的区域成功!!!";
			list = findByPid(3);
		}
		if (EmptyUtil.isNotEmpty(list)) {
			datas = new ArrayList<AppCitysDTO>();
			for (Citys citys : list) {
				datas.add(new AppCitysDTO(citys));
			}
			return new AjaxObj(1, msg, datas);
		}
		return new AjaxObj(0, "获取城市信息失败!");
	}

	@Override
	public AjaxObj findHasOpened() throws Exception {
		String hql = " from Citys c where c.status=1 and c.layer=2 ";
		List<Citys> list = citysDao.list(hql);
		List<AppCitysDTO> datas = null;
		if (EmptyUtil.isNotEmpty(list)) {
			datas = new ArrayList<AppCitysDTO>();
			for (Citys citys : list) {
				datas.add(new AppCitysDTO(citys));
			}
		}
		return new AjaxObj(1, "开通城市加载完成!", datas);
	}

	@Override
	public String findCitysIds(long cityid) throws Exception {
		String ids = citysDao.findCitysIds(cityid);
		return ids.replace(",", " ");
	}
}